package com.hnyfkj.jyindustry.common.utils;

import com.hnyfkj.jyindustry.common.dto.ShiroSessionDto;
import com.hnyfkj.jyindustry.common.exception.HnyfkjBusinessException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * @program: jyindustry
 * @description:shiro工具类
 * @author: zl
 * @create: 2020-07-09 18:05
 **/
public class ShiroUtils {

	public static Session getSession() {
		return SecurityUtils.getSubject().getSession();
	}

	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}

	public static ShiroSessionDto getUserSessionDto() {
		return (ShiroSessionDto) SecurityUtils.getSubject().getPrincipal();
	}

	public static Long getUserId() {
		return getUserSessionDto().getId();
	}

	public static void setSessionAttribute(final Object key, final Object value) {
		getSession().setAttribute(key, value);
	}

	public static Object getSessionAttribute(final Object key) {
		return getSession().getAttribute(key);
	}

	public static boolean isLogin() {
		return SecurityUtils.getSubject().getPrincipal() != null;
	}

	public static void logout() {
		SecurityUtils.getSubject().logout();
	}

	public static String getKaptcha(final String key) {
		final Object kaptcha = getSessionAttribute(key);
		if (kaptcha == null) {
			throw new HnyfkjBusinessException("验证码已失效");
		}
		getSession().removeAttribute(key);
		return kaptcha.toString();
	}

}
